import { create } from 'zustand';
import editorManager from '../utils/editorManager';
import useProjectStore from './projectStore';

const useEditorStore = create((set, get) => ({
  // 编辑器配置
  editorConfig: {
    theme: 'light', // 默认白天模式
    lineNumbers: true,
    wordWrap: true,
    fontSize: 14,
    tabSize: 4,
    autoCloseBrackets: true,
    highlightActiveLine: true,
  },
  
  
  updateEditorConfig: (newConfig) => {
    set((state) => ({
      editorConfig: { ...state.editorConfig, ...newConfig }
    }));
  },
  
  
  // 从文件系统加载内容到编辑器
  loadContentFromFileSystem: (content) => {
    editorManager.setValue(content);
  },
  
  // 获取编辑器当前内容（用户输入的内容）
  getCurrentCode: () => {
    return editorManager.getValue();
  },
  
  // 高亮错误行
  highlightErrorLine: (line, type = 'error') => {
    editorManager.highlightErrorLine(line, type);
  },
  
  // 清除错误高亮
  clearErrorHighlight: () => {
    editorManager.clearErrorHighlight();
  },
  
  
  // 立即保存当前内容
  saveNow: async () => {
    try {
      const currentContent = editorManager.getValue();
      if (!currentContent) return { success: false, error: '没有内容可保存' };
      
      const projectStore = useProjectStore.getState();
      const result = await projectStore.updateCurrentFileContent(currentContent);
      
      if (result.success) {
        console.log('手动保存成功:', result.data.fileName);
      }
      
      return result;
    } catch (error) {
      console.error('手动保存出错:', error);
      return { success: false, error: error.message };
    }
  },
}));

export default useEditorStore;
